# @Time : 2021/4/7 12:46
# @Author : Fioman 
# @Phone : 13149920693
"""
日志分析工具,包括日志格式化,还有就是保存的日志的数量限制
"""
import datetime
import logging
import os
import threading
from settings import DEBUG_DIR


def synchronized(func):
    """
    线程安全的装饰器,加一个线程锁
    :param func:
    :return:
    """
    func.__lock__ = threading.Lock()

    def lock_func(*args, **kwargs):
        with func.__lock__:
            return func(*args, **kwargs)

    return lock_func


class HdLogger(object):
    """
    单例日志类
    """
    __hdLogger__ = None
    __initFlag__ = False

    @synchronized
    def __new__(cls, *args, **kwargs):
        if cls.__hdLogger__ is None:
            cls.__hdLogger__ = object.__new__(cls)
        return cls.__hdLogger__

    def __init__(self):
        if not self.__initFlag__:
            print("HdLogger.__init__() 进行初始化")
            self.__initFlag__ = True
            self.debug = self.log_init().debug

    @staticmethod
    def log_check():
        """
        日志管理,如果日志目录不存在就创建,如果日志目录存在了,就将日志吸入到当前的目录中.日志的目录也保存到D盘固定位置,不要跟随项目走了.
        :return:
        """
        nowTime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")

        try:
            for root, _, filenames in os.walk(DEBUG_DIR):
                for filename in filenames:
                    day = filename[8:10]
                    month = filename[5:7]
                    now_day = nowTime[8:10]
                    now_month = nowTime[5:7]
                    if now_day == day and now_month != month:  # 如果天数对应得上,但是月数不同,就删除上个月同一天的日志信息
                        os.remove(os.path.join(DEBUG_DIR, filename))
        except Exception as e:
            errorInfo = "in log_check() error : {}".format(str(e))
            print(errorInfo)
        return nowTime

    def log_init(self):
        # 初始化日志模块,首先要先判断日志的目录是否存在,并且删除掉上一个月同一天的文件.日志目前只保存一个月的,最多31天的日志.
        nowTime = self.log_check()
        logger = logging.getLogger(__name__)
        logger.setLevel(level=logging.DEBUG)
        handler_ = logging.FileHandler(os.path.join(DEBUG_DIR, nowTime) + "_debug.txt", encoding="UTF-8")
        handler_.setLevel(logging.DEBUG)
        formatter_ = logging.Formatter("%(asctime)s - %(message)s")
        handler_.setFormatter(formatter_)
        logger.addHandler(handler_)
        return logger


if __name__ == '__main__':
    logger1 = HdLogger()
    logger2 = HdLogger()
    logger3 = HdLogger()
    print(logger1 is logger2, logger2 is logger3)
    logger1.debug("abs")
